//
//  MOFoodAppraiseViewController.m
//  MobileOffice
//
//  Created by 晓 on 2019/10/15.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOFoodAppraiseViewController.h"
#import "MOFoodAppraiseCell.h"
#import "MORefreshNormalHeader.h"
#import "MORefreshGifFooter.h"
#import "MOFoodDetailView.h"
#import "MOAppraiseViewController.h"

@interface MOFoodAppraiseViewController ()<UITableViewDelegate,UITableViewDataSource,YPSwipeTableViewCellDelegate>

@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NSMutableArray *buttonArray;

@property(nonatomic,strong) NSMutableArray *dataArray;

@property(nonatomic,assign)NSInteger currentPage;

@end

@implementation MOFoodAppraiseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title =  [self.isMy integerValue]==1?@"我的评价":@"菜品评价";
    self.view.backgroundColor = KWhiteColor;
    [self.view addSubview:self.tableView];
    
    [self initNav];
    
    if ([self.isMy integerValue]==0) {
        [self getData];
    }
    
}

-(void)initNav
{
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 30)];
    [button setTitle:@" 我的评价" forState:UIControlStateNormal];
    button.titleLabel.font = FONT_SIZE(13);
    [button setTitleColor:KBlueColor_2C94FF forState:UIControlStateNormal];
    [button setImage:IMAGE(@"my_comment") forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickMyComment) forControlEvents:UIControlEventTouchUpInside];
    
    if ([self.isMy integerValue]==0) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    }
    
}

-(void)clickMyComment
{
    MOFoodAppraiseViewController *vc = [[MOFoodAppraiseViewController alloc]init];
    vc.isMy = @"1";
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)getData
{
    //获取当前时间，日期
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
//    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    NSDate *monthagoData = [self getPriousorLaterDateFromDate:currentDate withMonth:-1];
    NSString *agoString = [dateFormatter stringFromDate:monthagoData];
    
    
    NSString *postUrl = [NSString stringWithFormat:@"%@?authorization=%@",GETDISHLIST,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    NSDictionary *dic = @{
                          @"userId":[MOUser sharedMOUser].userName,
                          @"startTime":agoString
                          };
    [PPNetworkHelper POST:postUrl parameters:dic success:^(id responseObject) {
        NSLog(@"评价列表：%@",responseObject);
        
        NSArray *dataArray = [NSArray array];
        if ([responseObject isKindOfClass:[NSArray class]]) {
            dataArray = responseObject;
            self.dataArray = [NSMutableArray array];
            for (int i = 0; i<dataArray.count; i++) {
                MOFoodAppraiseModel *model = [[MOFoodAppraiseModel alloc]init];
                model.cook = dataArray[i][@"cook"];
                model.restaurantName = dataArray[i][@"restaurantName"];
                model.dishName = dataArray[i][@"dishName"];
                model.dishId = dataArray[i][@"dishId"];
                model.restaurantId = dataArray[i][@"restaurantId"];
                [self.dataArray addObject:model];
            }
            [self.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"评价列表：%@",[error localizedDescription]);
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
    }];
}

-(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(int)month{
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMonth:month];
    NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];// NSGregorianCalendar
    NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0];
    return mDate;
    
}

-(void)getMyCommentData
{
    NSString *postUrl = [NSString stringWithFormat:@"%@?authorization=%@",GETDISHRATELIST,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    NSDictionary *dic = @{
                          @"userId":[MOUser sharedMOUser].userName,
                          @"pageNo":[NSString stringWithFormat:@"%ld",(long)self.currentPage],
                          @"limit":@"10"
                          };
    [PPNetworkHelper POST:postUrl parameters:dic success:^(id responseObject) {
        NSLog(@"我的评价列表：%@",responseObject);
        
        NSArray *dataArray = [NSArray array];
        if ([responseObject isKindOfClass:[NSArray class]]) {
            dataArray = responseObject;
            if (self.currentPage==1) {
                self.dataArray = [NSMutableArray array];
            }
            
            self.dataArray = [NSMutableArray array];
            for (int i = 0; i<dataArray.count; i++) {
                MOFoodAppraiseModel *model = [[MOFoodAppraiseModel alloc]init];
                model.cook = @"";
                model.restaurantName = dataArray[i][@"restaurantName"];
                model.dishName = dataArray[i][@"dishName"];
                model.createTime = dataArray[i][@"createTime"];
                model.star = dataArray[i][@"star"];
                model.isMy = @"1";
                model.dishId = dataArray[i][@"dishId"];
                model.restaurantId = dataArray[i][@"restaurantId"];
                model.content = [NSString passNullForString:dataArray[i][@"content"]];
                [self.dataArray addObject:model];
            }
            
            if (dataArray.count==0) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                [[ADShowMessage shareShowMessage] showTextOnly:@"暂无数据" showInView:self.view];
            }
            [self refreshEnding];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"我的评价列表：%@",[error localizedDescription]);
        [self refreshEnding];
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
    }];
}

#pragma mark -刷新，加载更多
//刷新
- (void)downloadAfaterDataSource{
    self.currentPage = 1;
    [self getMyCommentData];
}

//加载更多
- (void)downloadBeforeDataSource{
    self.currentPage++;
    [self getMyCommentData];
}

//刷新效果停止
- (void)refreshEnding{
    [self.tableView.mj_footer endRefreshing];
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"Cell";
    MOFoodAppraiseCell *foodOrderListCell = [[MOFoodAppraiseCell alloc]cellCreat:cellIdentifier AndArray:self.buttonArray andTableView:tableView cellIndexPath:indexPath andType:0];
    foodOrderListCell.delegate = self;
    MOFoodAppraiseModel *model = self.dataArray[indexPath.section];
    [foodOrderListCell setModel:model];
    return foodOrderListCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00000001;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - YPSwipeTableViewCelldidSelectBtnWithTag 代理
- (void)YPSwipeTableViewCelldidSelectBtnWithTag:(NSInteger)tag andIndexPath:(NSIndexPath *)indexPath{
    
    MOFoodAppraiseModel *model = self.dataArray[indexPath.section];
    if (tag==0) {
        
        MOAppraiseViewController *vc = [[MOAppraiseViewController alloc]init];
        vc.restaurantId = model.restaurantId;
        vc.dishId = model.dishId;
        vc.restaurantName = model.restaurantName;
        vc.dishName = model.dishName;
        vc.type = @"";
        
        if ([self.isMy integerValue]==1) {//评价详情
            vc.isDetail = @"1";
            vc.starValue = model.star;
            vc.content = model.content;
        }else{//评价
            vc.isDetail = @"0";
            __weak typeof (self)weakSelf = self;
            vc.commentEndBlock = ^{
                [weakSelf getData];
            };
        }
        
        [self.navigationController pushViewController:vc animated:YES];
        
        
    }else{//菜品详情
        [self getFoodDetailAndDishId:model.dishId];
    }
    
}


-(void)getFoodDetailAndDishId:(NSString *)dishId{
    
    NSString *postUrl = [NSString stringWithFormat:@"%@?authorization=%@",GETDISHBYID,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    NSDictionary *dic = @{
                          @"dishId":dishId
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [PPNetworkHelper POST:postUrl parameters:dic success:^(id responseObject) {
        NSLog(@"菜品详情：%@",responseObject);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            

            MOFoodDetailView *view = [[MOFoodDetailView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
            MOFoodDetailModel *detailModel = [[MOFoodDetailModel alloc]init];
            detailModel.foodNameStr = responseObject[@"data"][@"dishName"];
            detailModel.price = [NSString passNullForString:responseObject[@"data"][@"price"]];
            detailModel.cook = [NSString passNullForString:responseObject[@"data"][@"cook"]];
            detailModel.yuanLiao = [NSString passNullForString:responseObject[@"data"][@"material"]];
            detailModel.mark = [NSString passNullForString:responseObject[@"data"][@"mark"]];
            
            view.model = detailModel;
            [WINDOW addSubview:view];
            
        }else{
            [[ADShowMessage shareShowMessage]showTextOnly:@"获取失败，稍后重试" showInView:self.view];
        }
    } failure:^(NSError *error) {
        NSLog(@"菜品详情：%@",[error localizedDescription]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
    
    
}


#pragma mark -懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - StatusBarAndNavigationBarHeight) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = KGrayColor_f8f8f8;
        
        if ([self.isMy integerValue]==1) {
            _tableView.mj_header = [MORefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downloadAfaterDataSource)];
            _tableView.mj_footer = [MORefreshGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(downloadBeforeDataSource)];
            [_tableView.mj_header beginRefreshing];
        }
        
    }
    return _tableView;
}

-(NSMutableArray *)buttonArray
{
    
    UIButton *btn11 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 80)];
    btn11.backgroundColor = [UIColor whiteColor];
    if ([self.isMy integerValue]==1) {
        [btn11 setTitle:@"评价详情" forState:UIControlStateNormal];
    }else{
        [btn11 setTitle:@"评价" forState:UIControlStateNormal];
    }
    [btn11 setTitleColor:KBlackColor_2A2A2A forState:UIControlStateNormal];
    [btn11 setImage:[UIImage imageNamed:@"dingcan_blackComent"] forState:UIControlStateNormal];
    btn11.titleLabel.font = FONT_SIZE(12);
    btn11.userInteractionEnabled = NO;
    [btn11 SG_imagePositionStyle:(SGImagePositionStyleTop) spacing:5];
    
    UIButton *btn22 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 80)];
    btn22.backgroundColor = [UIColor whiteColor];
    [btn22 setTitle:@"菜品详情" forState:UIControlStateNormal];
    [btn22 setTitleColor:KBlackColor_2A2A2A forState:UIControlStateNormal];
    [btn22 setImage:[UIImage imageNamed:@"dingcan_blackDetail"] forState:UIControlStateNormal];
    btn22.titleLabel.font = FONT_SIZE(12);
    btn22.userInteractionEnabled = NO;
    [btn22 SG_imagePositionStyle:(SGImagePositionStyleTop) spacing:5];
    
    UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    btn2.backgroundColor = KGrayColor_f8f8f8;
    [btn2 addSubview:btn22];
    
    UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    btn1.backgroundColor = KGrayColor_f8f8f8;
    [btn1 addSubview:btn11];
    
    _buttonArray = [[NSMutableArray alloc]initWithObjects:btn1,btn2, nil];
    
    return _buttonArray;
}


@end
